import { http } from "../http";

export class Base {
  constructor(options) {
    this.options = options;
  }

  /**
   * 包装http
   * @param method
   * @param url
   * @param data
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  $http(method, url, data, params) {
    const { store, $axios } = this.options;
    let commit;
    if (store && store.commit) commit = store.commit;
    else
      commit = () => {
        // eslint-disable-next-line no-console
        console.log("no vuex please try other method");
      };
    commit("setAppLoading", true);
    let api;
    if ($axios) {
      if (method === "post") api = $axios.post(url, data);
    } else api = http(method, url, data, params);
    return api
      .then(data => {
        commit("setAppLoading", false);
        return data;
      })
      .catch(error => {
        commit("setAppLoading", false);
        console.error(error);
        return { errno: -1, errmsg: error.toString() };
      });
  }
}
